<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue自定义指令的使用与实践</title>
    <!-- 引入代码高亮的样式 -->
    <link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/monokai-sublime.min.css" rel="stylesheet" />
    <style>
      .img {
        width: 300px;
        height: 200px;
        background-size: 100%;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- v-img -->
      <div class="img" v-for="(img, index) in imgList" :key="index" v-img:async.lazy="img.url"></div>
      <!-- v-highlight -->
      <div>
        <pre>
          <code v-highlight class="javascript">function init(){ $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }</code></pre>
      </div>
    </div>
  </body>
  <!-- 引入框架 -->
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <!-- 引入插件 -->
  <script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
  <script>
    window.onload = function() {
      // 写在new Vue()之前;可以在全局使用。
      Vue.directive('img', {
        inserted: function(el, binding) {
          // =值
          // console.log(binding.value);
          // :参数
          // console.log(binding.arg);
          // .修饰符
          // console.log(binding.modifiers);
          // #FFFFFF
          var color = Math.floor(Math.random() * 1000000);
          el.style.backgroundColor = '#' + color;

          var img = new Image();
          img.src = binding.value;
          img.onload = function() {
            setTimeout(function() {
              el.style.backgroundImage = 'url(' + binding.value + ')';
            }, 1000);
          };
        },
      });
      Vue.directive('highlight', {
        inserted: function(el) {
          console.log(el);
          hljs.highlightBlock(el);
        },
      });
      new Vue({
        el: '#app',
        data: {
          msg: 'hello',
          imgList: [
            {
              url: 'http://img.zcool.cn/community/013ab856f4c9cd6ac72579487b51cc.jpg',
            },
            {
              url: 'http://s4.sinaimg.cn/mw600/001oLWdezy6LkMvA3RN63&690',
            },
            {
              url: 'http://img.zcool.cn/community/01d24457888b050000012e7e4c119a.png',
            },
          ],
        },
      });
    };
  </script>
</html>
